package com.wxj.book.cms.controller;

import com.github.pagehelper.PageInfo;
import com.wxj.book.cms.common.ServerResponse;
import com.wxj.book.cms.pojo.Book;
import com.wxj.book.cms.pojo.Category;
import com.wxj.book.cms.service.BookService;
import com.wxj.book.cms.service.CategoryService;
import com.wxj.book.cms.vo.BookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 跳转到书籍集合页面
     */
    @RequestMapping("page/book")
    public String bookPage(@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                           ModelMap modelMap) {
        // 查询所有的图书
        PageInfo<BookVo> bookVos = bookService.getAll(pageNum, pageSize);
        modelMap.addAttribute("bookVos", bookVos);
        // 查询所有分类
        List<Category> categories = categoryService.getAll();
        modelMap.addAttribute("categories", categories);
        return "book";
    }

    /**
     * 更新书籍或者添加书籍
     */
    @PostMapping("book/updateBook")
    @ResponseBody
    public ServerResponse updateBook(Book book) {
        if (book == null) {
            return ServerResponse.createByErrorMessage("更新失败");
        }
        int result = bookService.updateBook(book);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");

    }
}
